package org.onvivals.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.onvivals.module.system.entity.SysRole;
import org.onvivals.module.system.entity.SysUserRole;
import org.onvivals.module.system.mapper.SysRoleMapper;
import org.onvivals.module.system.service.ISysRoleService;
import org.onvivals.module.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService{

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public List<SysRole> listByUserId(Long userId) {
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .select(SysUserRole::getUserId)
                .leftJoin(SysUserRole.class,SysUserRole::getRoleId,SysRole::getRoleId)
                .eq(SysUserRole::getUserId,userId);
        return roleMapper.selectJoinList(SysRole.class,wrapper);
    }

    @Override
    public boolean saveBatchUserRole(Long userId, Set<Long> roleIds) {
        // 先删除用户角色
        sysUserRoleService.removeByUserId(userId);
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        roleIds.forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoles.add(sysUserRole);
        });
        return sysUserRoleService.saveBatch(sysUserRoles);
    }
}
